# Copyright (c) 2025, hzmes and contributors
# For license information, please see license.txt

import frappe
from frappe import _
from frappe.utils import cstr, flt, cint, get_first_day, get_last_day

def execute(filters=None):
	columns, data = get_columns(filters), get_data(filters)
	return columns, data

def get_columns(filters):
	columns = [
		{"label": _("Bom Version"),"fieldtype": "Data","fieldname": "bom_version","width": 100,},
		{"label": _("Product Code"),"fieldtype": "Data","fieldname": "product_code","width": 100,},
		{"label": _("Product Name"),"fieldtype": "Data","fieldname": "product_name","width": 100,},
		{"label": _("Product Description"),"fieldtype": "Data","fieldname": "product_description","width": 130,},
		{"label": _("User Org"),"fieldtype": "Data","fieldname": "user_org","width": 120,},
		{"label": _("Item Code"),"fieldtype": "Data","fieldname": "item_code","width": 120,},
		{"label": _("Item Name"),"fieldtype": "Data","fieldname": "item_name","width": 120,},
		{"label": _("Item Description"),"fieldtype": "Data","fieldname": "item_description","width": 120,},
		{"label": _("Material Type"),"fieldtype": "Data","fieldname": "material_type","width": 80,},
		{"label": _("Child Item Property"),"fieldtype": "Data","fieldname": "child_item_property","width": 80,},
	]
	return columns

def get_data(filters):
	# 获取filters
	product_code = filters.get('product_code')
	user_org = filters.get('user_org')
	return get_bom_items(product_code, user_org)

@frappe.whitelist()
def get_bom_items(product_code, user_org, max_depth=10):
    """
    递归获取BOM的所有子项
    
    参数:
        product_code: 产品代码
        max_depth: 最大递归深度，防止无限循环
    
    返回:
        包含所有子项的列表
    """
    # 使用参数化查询防止SQL注入
    sql = """
        SELECT p.bom_version, p.product_code, p.product_name, p.product_description, p.user_org,
               c.item_code, c.item_name, c.item_description, c.child_item_property, c.material_type 
        FROM `tabHSF BOM` p 
        JOIN `tabHSF BOM Child` c ON p.`name` = c.parent
        WHERE p.product_code = %s AND p.user_org = %s
    """
    
    result = frappe.db.sql(sql, (product_code, user_org), as_dict=1)
    
    final_items = []
    to_process = []  # 需要进一步处理的项
    
    for item in result:
        if item["child_item_property"] == "1":
            final_items.append(item)
        else:
            to_process.append(item)
    
    # 递归处理子项，但限制最大深度
    if to_process and max_depth > 0:
        for item in to_process:
            child_items = get_bom_items(item["item_code"], item["user_org"], max_depth - 1)
            final_items.extend(child_items)
    
    return final_items

